package demo0921;

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class T1_0530 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查找的目录：");
        String rootpath = scanner.next();
        if (rootpath == null || rootpath.isEmpty()) {
            System.out.println("目录不能为空");
            return;
        }
        File rootfile = new File(rootpath);
        if (!rootfile.isDirectory()) {
            System.out.println("不是目录");
            return;
        }

        System.out.println("请输入要找出文件名中含的字符串：");
        String token= scanner.next();
        if (token == null || token.isEmpty()) {
            System.out.println("目标文件不合法");
            System.out.println("token:" + token);
            return;
        }

        ArrayList<File> arrayList = new ArrayList<>();
        scanDir(rootfile,token,arrayList);
        if (arrayList.isEmpty()) {
            System.out.println("没有找到符合条件的文件。");
        }else {
            for (File file : arrayList) {
                System.out.println("是否要删除文件" + file.getAbsoluteFile() + "（y/n）");
                String choice = scanner.next();
                if (choice == null || choice.isEmpty()) {
                    System.out.println("选择有误");
                } else {
                    if (choice.equals("y")) {
                        file.delete();
                    }
                }
            }
        }

    }

    private static void scanDir(File rootfile, String token, ArrayList<File> arrayList) {
        if (rootfile == null || !rootfile.exists() || !rootfile.isDirectory()) {
            return;
        }
        File[] files = rootfile.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                scanDir(f,token,arrayList);
            }else {
                if (f.getName().contains(token)) {
                    System.out.println(token);
                    arrayList.add(f.getAbsoluteFile());
                }
            }
        }
    }
}
